<?php
/**
 * Created by PhpStorm.
 * User: wuxiang
 * Date: 2016/8/30
 * Time: 14:18
 */

namespace Matelist\Controller;

use Common\Controller\AdminbaseController;
use Common\Libiary\BaseApiHttp;
use Common\Libiary\LogEX;
use Common\Libiary\Uploadify;
use Common\Libiary\WechatMaterial;
use Think\Exception;

class MatelistController extends AdminbaseController
{

    public $data = [];
    public $arr = [];
    public $res = [];
    public $rest = [];
    public $result;
    public $list;
    public $fanAcount;
    public $url;
    public $setUrl;
    public $page;

    /**
     * 同步素材
     */
    function index()
    {

        $strarExpirationTime = I('strarExpirationTime', '', 'trim');

        $endExpirationTime = I('endExpirationTime', '', 'trim');

        $type = I('type', 'news', 'trim');
        $sync = I('data');

        $materialSql = M('WechatMaterial');

        //同步素材
        if ($sync) {

            //获取access_token
            $material = new WechatMaterial();
            $accessTokenInfo = $material->getToken();

            LogEX::i('获取token值',['data'=>$accessTokenInfo],__FILE__,__LINE__);
            if(!$accessTokenInfo){
                die(json_encode(['errno' => 2, 'msg' => '未获取到token']));
            }
            /**
             * 下面是判断数据库里是否有数据
             */
            set_time_limit(0);
            $typeInfo = ['news', 'image', 'voice', 'video'];
            $page = 20;
            foreach ($typeInfo as $v) {
                //需要拉取次数
                try{
                    $i = 0;
                    while (1) {
                        $result = $material->get_article_list($v, $page * $i, $page, $accessTokenInfo);

                        if (empty($result['item'])) {
                            break;
                        }
                        $newsData = $material->import_opearte($v, $result['item']);

                        foreach($newsData as $row){
                            $pk = $materialSql->add($row);
                        }

                        $i++;
                    }

                }catch(\Exception $e){

                    if($e){

                        continue;
                    }
                }
            }

            if($pk){
                die(json_encode(['errno' => 0, 'msg' => '更新完毕']));
            }else{
                die(json_encode(['errno' => 0, 'msg' => '更新完毕']));
            }
        }

        $sql = 'type = ' . "'" . $type . "'";
        $sql .= $strarExpirationTime == '' ? '' : ' AND meta_add_time > ' . strtotime($strarExpirationTime);
        $sql .= $endExpirationTime == '' ? '' : ' AND meta_add_time < ' . strtotime($endExpirationTime);

        $materialCount = $materialSql->where($sql)->count();
        $Page = new \Think\Page($materialCount, 20, $_POST);

        $show = $Page->show();
        $arr = $materialSql->where($sql)->order('meta_add_time desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        foreach ($arr as $k => $v) {
            $res = json_decode($v['item'], true);
            $arr[$k]['itemInfo'] = $res;
            if($v['type']=='news') {
                foreach ($res['news_item'] as $key => $val) {
                    if ($val['thumb_url']) {
                        $arr[$k]['itemInfo']['news_item'][$key]['thumb_url'] = $val['thumb_url'];//substr($val['thumb_url'], 0, strpos($val['thumb_url'], '?'));
                    }
                }
            }
            if($v['type']=='image'){
                $arr[$k]['itemInfo']['url'] = $res['url'];//substr($res['url'], 0, strpos($res['url'], '?'));
            }
        }
        $this->assign('pager', $show);
        $mateList = getMateType();
        $view = M('WechatView');
        $viewList = $view->select();

        $this->assign('viewList', $viewList);
        $this->assign('list', $arr);
        $this->assign('mate', $mateList);
        $this->assign('typeInfo', $type);
        $this->assign('strarExpirationTime', $strarExpirationTime);
        $this->assign('endExpirationTime', $endExpirationTime);
        $this->assign('materialCount', $materialCount);

        $this->display();
    }


    /**
     * 发送手机预览
     */
    function sendPreview()
    {
        $openid = I('openid');
        $type = I('type');
        $media_id = I('media_id');

        $material = new WechatMaterial();
        $accessToken = $material->getToken();

        $res = $material->viewInfo($openid, $type, $media_id, $accessToken);

        if ($res['errcode'] == 0) {
            $succ['errno'] = 1;
            return $this->ajaxReturn($succ);
        }
    }


    function saveOpenId(){

        $openid = I('openid');
        $remark = I('remark');
        //组合发送数据

        try{
            $view = M('WechatView');
            $data = [];

            $data['open_id'] = $openid;
            $data['remark'] = $remark;
            $data['add_time'] = time();
            $pk = $view->add($data);

        }catch (\Exception $e){
            if($e){
                $succ['errno'] = 2;
                return $this->ajaxReturn($succ);
            }
        }
        if($pk){
            $succ['errno'] = 1;
            return $this->ajaxReturn($succ);
        }

    }

    function getUrl($url){
        if($url){
            $urlInfo = strpos('?',$url);
            return $urlInfo;
        }
    }
}